import re

from django import forms
from django.shortcuts import render
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from web.utils.Bootstrap import BootStrapForm,BootStrapModelForm

from web import models
from web.models import Usersinfo
from project01 import settings 

class RegisterModelform(forms.ModelForm):

    password=forms.CharField(label='密码',widget=forms.PasswordInput)
    confirm_password=forms.CharField(label='确认密码',widget=forms.PasswordInput)
    code=forms.CharField(label='验证码',widget=forms.TextInput)
    mobile_phone=forms.CharField(label='手机号', validators=[RegexValidator (r'^1[3-9]\d{9}$','手机格式错误')])
    class Meta:
        model=Usersinfo
        fields=['name','email','password','confirm_password','mobile_phone','code']
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name, field in self.fields.items():
            
            # 字段中有属性，保留原来的属性，没有属性，才增加。
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = f'请输入{field.label}'
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    "placeholder": f'请输入{field.label}'
                }



class SendSmsModelform(forms.Form):
    mobile_phone=forms.CharField(label='手机号',validators=[RegexValidator(r'^1[3-9]\d{9}$','手机格式错误')])
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
    def clean_mobile_phone(self):
        Mobile_phone=self.cleaned_data['mobile_phone']
        exists=Usersinfo.objects.filter(mobile_phone=Mobile_phone).exists()
        if exists:
            raise ValidationError('手机号存在')
        tpl=self.request.GET.get('tpl')
        tpl_id=settings.TENCENT_SMS_TEMPLATE.get('tpl')
        if not tpl_id:
            raise ValidationError('模板不存在')



class LoginForm(BootStrapForm):
    name=forms.CharField(label='用户名',max_length=64)
    password=forms.CharField(label='密码',widget=forms.PasswordInput)
    code=forms.CharField(label='验证码',max_length=32)
    
    
    def __init__(self,request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request=request
    def clean_code(self):
        code=self.cleaned_data.get('code')
        session_code=self.request.session.get('imgcode')
        if code is None or session_code is None:  
            raise ValidationError('验证码输入不完整或会话中缺少验证码') 
        if code.strip().upper()!=session_code.strip().upper():
            raise ValidationError('验证码输入错误')
        return code